/**
 * @author Uriah Thornes, Jerod Pekuri
 */

// Using Fleegix as per project requirements :(
fleegix.date.timezone.zoneFileBasePath = 'lib/timezones';
fleegix.date.timezone.init();

var now;
var hoursOffset = 0;

function initClock() {
  var fps = 60;
  drawClock();
  setInterval("drawClock()", 1000 / fps);
}

function drawClockface() {
  var ctx = document.getElementById('clock').getContext('2d');
  if (ctx) {
    ctx.save();
    ctx.beginPath();
    ctx.arc(150, 150, 125, 0, 2*Math.PI, false);
    ctx.lineWidth = 4;
    ctx.stroke();
    ctx.closePath();

    // Draw seconds ticks
    var tickSize = 3;
    ctx.translate(150,150);
    for (var i=0; i<=60; i++) {
      ctx.beginPath();
      if (i % 15 == 0)
        tickSize = 8;
      else if (i % 5 == 0)
        tickSize = 5;
      ctx.arc(0,125,tickSize,0,2*Math.PI,true);
      tickSize = 3;
      ctx.fill();
      ctx.rotate(2*Math.PI/60);
    }
    ctx.restore();
  }
}

function drawClock() {
  now = new fleegix.date.Date();

  // Calculate the angles of each hand
  var milliseconds = now.getMilliseconds() * 2 * Math.PI / 1000;
  var seconds = (now.getSeconds() * Math.PI) / 30 + milliseconds/60;
  var minutes = (now.getMinutes() * Math.PI) / 30 + seconds/60;
  var hours = ((now.getHours() + hoursOffset % 12) * Math.PI) / 6 + minutes/12;
  /*document.getElementById('test').innerHTML = now  + " " +
    (now.getSeconds() + now.getMilliseconds()/1000) + " seconds";*/

  var ctx = document.getElementById('clock').getContext('2d');
  if (ctx) {
    ctx.save();
    ctx.clearRect(0, 0, 300, 300);
    drawClockface();
    ctx.translate(150, 150);
    ctx.rotate(-Math.PI/2); // Set default angle to "12 o'clock"

    // Hour hand
    ctx.save();
    ctx.rotate(hours);
    ctx.lineWidth = 10;
    ctx.lineCap = 'round';
    ctx.beginPath();
    ctx.moveTo(-10, 0);
    ctx.lineTo(75, 0);
    ctx.stroke();
    ctx.restore();
    
    // Minute hand
    ctx.save();
    //ctx.rotate(min*Math.PI/30 + sec*Math.PI/1800);
    ctx.rotate(minutes);
    ctx.lineWidth = 7;
    ctx.lineCap = 'round';
    ctx.beginPath();
    ctx.moveTo(-20, 0);
    ctx.lineTo(100, 0);
    ctx.stroke();
    ctx.restore();

    // Seconds hand
    ctx.save();
    ctx.rotate(seconds);
    ctx.lineWidth = 3;
    ctx.lineCap = 'round';
    ctx.beginPath();
    ctx.moveTo(-30, 0);
    ctx.lineTo(115, 0);
    ctx.stroke();
    ctx.restore();
    
    // Milliseconds hand
    ctx.save();
    ctx.rotate(milliseconds);
    ctx.lineWidth = 1;
    ctx.lineCap = 'round';
    ctx.beginPath();
    ctx.moveTo(-40, 0);
    ctx.lineTo(125, 0);
    ctx.stroke();
    ctx.restore();
    
    ctx.restore();
  }
}

function changeTimezone() {
  var timeZone = document.getElementById('timeZone').value;
  var date = new fleegix.date.Date(new Date());
  var offset = date.getTimezoneOffset() / 60;
  if (timeZone)
    date.setTimezone(timeZone);
  hoursOffset = offset - date.getTimezoneOffset() / 60;
  drawClock();
}

